#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>

int uart_open() // 打开串口文件
{
    int fd = open("/dev/ttyCH341USB0", O_RDWR | O_NOCTTY);
    if (fd == -1) // 判断是否打开成功
    {
        perror("uart file open error!\n");
        return -1;
    }
    else
    {
        printf("open success!\n");
    }

    if (0 == isatty(STDIN_FILENO)) // 判断是否是设备节点文件
    {
        printf("isatty error!\n");
        return -1;
    }
    else
    {
        printf("isatty success!\n");
    }
    return fd;
}

int uart_init(int fd) // 配置串口文件
{
    struct termios oldtio = {0};
    struct termios newtio = {0};
    tcgetattr(fd, &oldtio);
    // 设置波特率为115200
    newtio.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
    newtio.c_iflag = 0; // IGNPAR | ICRNL
    newtio.c_oflag = 0;
    newtio.c_lflag = 0; // ICANON
    newtio.c_cc[VTIME] = 0;
    newtio.c_cc[VMIN] = 1;
    tcflush(fd, TCIOFLUSH);
    tcsetattr(fd, TCSANOW, &newtio);
    // 设置为非阻塞模式，这个在读串口的时候会用到
    fcntl(fd, F_SETFL, O_NONBLOCK);
    return 0;
}

int uart_read(int fd) // 读取串口文件
{
    char buffer[10];
    int ret = read(fd, buffer, sizeof(buffer));
    if (ret == -1)
    {
        return -1;
    }
    else
    {
        return atoi(buffer);
    }
}
int flag=0;
int main()
{
    int order = 0;
    int uart_fd; // 用于打开串口文件
    uart_fd = uart_open();
    if (uart_fd == -1)
    {
        return 0;
    }
    if (uart_init(uart_fd) == -1)
    {
        printf("uart init error\n");
        goto aa;
    }
    tcflush(uart_fd, TCIOFLUSH);
    printf("it is ready!\n");
    while (1)
    {
        order = uart_read(uart_fd);
        switch (order)
        {
        case 1:
            printf("打开灯光\n");
            system("./led 1");
            break;
        case 2:
            printf("关闭灯光\n");
            system("./led 2");
            break;
        case 3:
            printf("打开窗帘\n");
            system("./motor 1");
            break;
        case 4:
            printf("关闭窗帘\n");
            system("./motor 2");
            break;
        case 5:
            printf("关闭程序\n");
            goto aa;
        case 6:
            printf("调整灯光角度\n");
            flag++;
            if(flag%3==1)
            {
                system("./sg90 2 90");
            }else if(flag%3==2)
            {
                system("./sg90 2 180");
            }else if(flag%3==0)
            {
                system("./sg90 2 0");
            }
            break;
        case 7:
            printf("感知温度\n");
            system("./pcf /dev/pcf8591 1");
            break;
        case 8:
            printf("感知光强\n");
            system("./pcf /dev/pcf8591 0");
            break;
        }
    }
aa:
    close(uart_fd);
    return 0;
}